#include	"Wiimote4Virtools.h"
#include	"WiimInit.h"

CKObjectDeclaration *FillBehaviorWiimInit()
{
    CKObjectDeclaration *od = CreateCKObjectDeclaration ( "WiimInit" );
    od->SetDescription ( "Initializes a number of Wiimotes." );
    od->SetCategory ( "Wiimote" );
    od->SetType ( CKDLL_BEHAVIORPROTOTYPE );
    od->SetGuid ( WIIMINIT_GUID );
    od->SetAuthorGuid ( AUTHOR_GUID );
    od->SetAuthorName ( "Jonathan DERROUGH" );
    od->SetVersion ( 0x00000001 );
    od->SetCreationFunction ( CreateWiimInitProto );
    //od->SetCompatibleClassId ( CKCID_3DENTITY );
    return od;
}

CKERROR CreateWiimInitProto ( CKBehaviorPrototype **pproto)
{
    CKBehaviorPrototype *proto = CreateCKBehaviorPrototype("WiimInit");

    if(!proto)
		return (CKERR_OUTOFMEMORY);

    proto->DeclareInput("In");
    proto->DeclareOutput("True");
		proto->DeclareOutput("False");
		
    proto->DeclareInParameter("Number of wiimotes", CKPGUID_INT );
    proto->DeclareInParameter("Motion detection", CKPGUID_BOOL );

    proto->SetFlags(CK_BEHAVIORPROTOTYPE_NORMAL);
    proto->SetFunction(WiimInit);
    //proto->SetBehaviorFlags(CKBEHAVIOR_TARGETABLE);
    
    *pproto = proto;
    return (CK_OK);
}

int WiimInit(const CKBehaviorContext& behcontext)
{
	CKBehavior* beh = behcontext.Behavior;

	beh->ActivateInput(0, FALSE);	// deactivation

	// Wiimote(s) already initialized ?
	if (g_wiimotes.size() > 0)
	{
		beh->ActivateOutput(0);
		return (CKBR_OK);
	}

	g_wiimotes = HIDDevice::ConnectToHIDDevices<Wiimote>();

	// Wiimote(s) present ?
	if (g_wiimotes.size() < 1)
	{
		beh->ActivateOutput(1);
		return (CKBR_OK);
	}
	
	// Get the number of Wiimotes we are using
	int nb_wiimotes = 0;
	beh->GetInputParameterValue(0, &nb_wiimotes);

	// Do we want motion detection ?
	CKBOOL motion_detection = 0;
	beh->GetInputParameterValue(1, &motion_detection);

	
	for (int count = 0; count != nb_wiimotes; count++)
	{
		g_wiimotes[count].StartListening();       // Start listening to input reports
		if (motion_detection == TRUE)
			g_wiimotes[count].RequestMotionData();    // Request the remote start sending back motion data
	}

	beh->ActivateOutput(0);
	return (CKBR_OK);
}